using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace Toolbox.Model.Settings
{
    /// <summary>
    /// 配置管理工具类
    /// 负责所有配置的读取、保存和管理
    /// 作者：huobing
    /// </summary>
    public class ConfigManager
    {
        private static ConfigManager? _instance;
        private readonly string _configPath;
        private Dictionary<string, string> _settings;
        private readonly object _lockObject = new object();

        /// <summary>
        /// 单例实例
        /// </summary>
        public static ConfigManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ConfigManager();
                }
                return _instance;
            }
        }

        /// <summary>
        /// 私有构造函数
        /// </summary>
        private ConfigManager()
        {
            _configPath = Path.Combine(Application.StartupPath, "Conf", "Settings.conf");
            _settings = new Dictionary<string, string>();
            LoadAllSettings();
        }

        /// <summary>
        /// 加载所有配置
        /// </summary>
        private void LoadAllSettings()
        {
            try
            {
                if (File.Exists(_configPath))
                {
                    string[] lines = File.ReadAllLines(_configPath);
                    _settings = new Dictionary<string, string>();
                    
                    foreach (string line in lines)
                    {
                        // 跳过空行和注释行（以#开头）
                        if (string.IsNullOrWhiteSpace(line) || line.Trim().StartsWith("#"))
                        {
                            continue;
                        }
                        
                        // 解析key=value格式
                        int equalIndex = line.IndexOf('=');
                        if (equalIndex > 0)
                        {
                            string key = line.Substring(0, equalIndex).Trim();
                            string value = line.Substring(equalIndex + 1).Trim();
                            _settings[key] = value;
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                // 配置文件读取失败，使用默认配置
                _settings = new Dictionary<string, string>();
            }
        }

        /// <summary>
        /// 保存所有配置到文件
        /// </summary>
        private void SaveAllSettings()
        {
            lock (_lockObject)
            {
                try
                {
                    // 确保配置文件所在的目录存在
                    string? configDir = Path.GetDirectoryName(_configPath);
                    if (!string.IsNullOrEmpty(configDir) && !Directory.Exists(configDir))
                    {
                        Directory.CreateDirectory(configDir);
                    }
                    
                    // 读取现有文件以保留注释
                    List<string> existingLines = new List<string>();
                    if (File.Exists(_configPath))
                    {
                        existingLines.AddRange(File.ReadAllLines(_configPath));
                    }
                    
                    // 创建新的文件内容
                    List<string> newLines = new List<string>();
                    Dictionary<string, bool> processedKeys = new Dictionary<string, bool>();
                    
                    // 处理现有行，保留注释并更新值
                    foreach (string line in existingLines)
                    {
                        if (string.IsNullOrWhiteSpace(line) || line.Trim().StartsWith("#"))
                        {
                            // 保留空行和注释
                            newLines.Add(line);
                        }
                        else
                        {
                            // 解析key=value格式
                            int equalIndex = line.IndexOf('=');
                            if (equalIndex > 0)
                            {
                                string key = line.Substring(0, equalIndex).Trim();
                                if (_settings.ContainsKey(key))
                                {
                                    // 更新现有键的值
                                    newLines.Add($"{key}={_settings[key]}");
                                    processedKeys[key] = true;
                                }
                                else
                                {
                                    // 保留不再存在的键
                                    newLines.Add(line);
                                }
                            }
                            else
                            {
                                // 保留无法解析的行
                                newLines.Add(line);
                            }
                        }
                    }
                    
                    // 添加新的键值对
                    foreach (var kvp in _settings)
                    {
                        if (!processedKeys.ContainsKey(kvp.Key))
                        {
                            newLines.Add($"{kvp.Key}={kvp.Value}");
                        }
                    }
                    
                    File.WriteAllLines(_configPath, newLines);
                }
                catch (System.Exception)
                {
                    // 保存失败忽略
                }
            }
        }

        /// <summary>
        /// 获取指定键的配置值
        /// </summary>
        /// <param name="key">配置键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值或默认值</returns>
        public string GetSetting(string key, string defaultValue = "")
        {
            if (_settings.TryGetValue(key, out string? value) && value != null)
            {
                return value;
            }
            return defaultValue;
        }

        /// <summary>
        /// 获取指定页签的配置值
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值或默认值</returns>
        public string GetTabSetting(string tabPrefix, string key, string defaultValue = "")
        {
            return GetSetting($"{tabPrefix}.{key}", defaultValue);
        }

        /// <summary>
        /// 获取指定页签的字符串配置值
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置值或默认值</returns>
        public string GetStringTabSetting(string tabPrefix, string key, string defaultValue = "")
        {
            return GetTabSetting(tabPrefix, key, defaultValue);
        }

        /// <summary>
        /// 保存单个配置值
        /// </summary>
        /// <param name="key">配置键名</param>
        /// <param name="value">配置值</param>
        public void SaveSetting(string key, string value)
        {
            lock (_lockObject)
            {
                _settings[key] = value;
                SaveAllSettings();
            }
        }

        /// <summary>
        /// 保存指定页签的配置值
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        /// <param name="value">配置值</param>
        public void SaveTabSetting(string tabPrefix, string key, string value)
        {
            SaveSetting($"{tabPrefix}.{key}", value);
        }

        /// <summary>
        /// 获取整数值配置
        /// </summary>
        /// <param name="key">配置键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置的整数值或默认值</returns>
        public int GetIntSetting(string key, int defaultValue = 0)
        {
            string value = GetSetting(key);
            if (int.TryParse(value, out int intValue))
            {
                return intValue;
            }
            return defaultValue;
        }

        /// <summary>
        /// 获取指定页签的整数值配置
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置的整数值或默认值</returns>
        public int GetIntTabSetting(string tabPrefix, string key, int defaultValue = 0)
        {
            return GetIntSetting($"{tabPrefix}.{key}", defaultValue);
        }

        /// <summary>
        /// 保存整数值配置
        /// </summary>
        /// <param name="key">配置键名</param>
        /// <param name="value">整数值</param>
        public void SaveIntSetting(string key, int value)
        {
            SaveSetting(key, value.ToString());
        }

        /// <summary>
        /// 保存指定页签的整数值配置
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        /// <param name="value">整数值</param>
        public void SaveIntTabSetting(string tabPrefix, string key, int value)
        {
            SaveTabSetting(tabPrefix, key, value.ToString());
        }
        
        /// <summary>
        /// 获取布尔值配置
        /// </summary>
        /// <param name="key">配置键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置的布尔值或默认值</returns>
        public bool GetBoolSetting(string key, bool defaultValue = false)
        {
            string value = GetSetting(key);
            if (bool.TryParse(value, out bool boolValue))
            {
                return boolValue;
            }
            return defaultValue;
        }
        
        /// <summary>
        /// 获取指定页签的布尔值配置
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns>配置的布尔值或默认值</returns>
        public bool GetBoolTabSetting(string tabPrefix, string key, bool defaultValue = false)
        {
            return GetBoolSetting($"{tabPrefix}.{key}", defaultValue);
        }
        
        /// <summary>
        /// 保存布尔值配置
        /// </summary>
        /// <param name="key">配置键名</param>
        /// <param name="value">布尔值</param>
        public void SaveBoolSetting(string key, bool value)
        {
            SaveSetting(key, value.ToString());
        }
        
        /// <summary>
        /// 保存指定页签的布尔值配置
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        /// <param name="value">布尔值</param>
        public void SaveBoolTabSetting(string tabPrefix, string key, bool value)
        {
            SaveTabSetting(tabPrefix, key, value.ToString());
        }

        /// <summary>
        /// 检查配置是否存在
        /// </summary>
        /// <param name="key">配置键名</param>
        /// <returns>是否存在</returns>
        public bool HasSetting(string key)
        {
            return _settings.ContainsKey(key);
        }

        /// <summary>
        /// 检查指定页签的配置是否存在
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        /// <returns>是否存在</returns>
        public bool HasTabSetting(string tabPrefix, string key)
        {
            return HasSetting($"{tabPrefix}.{key}");
        }

        /// <summary>
        /// 删除配置
        /// </summary>
        /// <param name="key">配置键名</param>
        public void RemoveSetting(string key)
        {
            lock (_lockObject)
            {
                if (_settings.ContainsKey(key))
                {
                    _settings.Remove(key);
                    SaveAllSettings();
                }
            }
        }

        /// <summary>
        /// 删除指定页签的配置
        /// </summary>
        /// <param name="tabPrefix">页签前缀</param>
        /// <param name="key">配置键名</param>
        public void RemoveTabSetting(string tabPrefix, string key)
        {
            RemoveSetting($"{tabPrefix}.{key}");
        }
    }
}